package com.yc.thread.interrupte;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 尝试中断ReentrantLock
 */
public class InterruptReentrantLock {

    public static void main(String[] args) {
        InterruptReentrantLock t = new InterruptReentrantLock();
//        t.m2();
        t.m3();
    }

    ReentrantLock mylock = new ReentrantLock();
    public void m1() {

        mylock.lock();
//        Thread.sleep(3000);
        mylock.unlock();
    }

    public void m2() {
        Object o = new Object();
        Thread t1 = new Thread(() -> {
            synchronized(o) {
                System.out.println("--------------1-");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("--------------2-");
            }
        });
        t1.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t1.interrupt();
        try {
            Thread.sleep(1);//这里如果不暂停一下，下面会检测到:刚被打断，但中断标记还没被清除的很短暂的一个中间状态
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(t1.isInterrupted());//false。wait被中断后，中断标记被清除

    }

    public void m3() {
        Object o = new Object();
        Thread t1 = new Thread(() -> {
            try {
                mylock.lockInterruptibly();
                System.out.println("--------------1-");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("--------------2-");

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                mylock.unlock();
            }

        });
        t1.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t1.interrupt();
        try {
            Thread.sleep(1);//这里如果不暂停一下，下面会检测到:刚被打断，但中断标记还没被清除的很短暂的一个中间状态
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(t1.isInterrupted());//false。wait被中断后，中断标记被清除

    }
}
